package com.example.blog.module.component;

import com.example.blog.module.entity.Article;
import com.example.blog.module.entity.VO.ViewCountQuery;
import com.example.blog.module.mapper.ArticleMapper;
import com.example.blog.module.service.ThreadService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 定时任务
 * @author zjx
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class Task {

    private final RedisTemplate<String, String> redisTemplate;

    private final ArticleMapper articleMapper;

    private final MyElasticsearchRepository myElasticsearchRepository;

    /**
     * 一分钟一次
     */
    @Scheduled(cron="0 * * * * ?")
    public void updateViewCount(){
        log.info("更新文章阅读数");
        Set<String> keys = redisTemplate.keys("VIEW_COUNT"+"*");
        if(!keys.isEmpty()){
            for (String key : keys) {
                String ArticleIdStr = key.substring("VIEW_COUNT".length(), key.length());
                String viewCount = redisTemplate.opsForValue().get(key);
                long articleId = Long.parseLong(ArticleIdStr);
                articleMapper.updateCountAndHotness(articleId,viewCount);

                //同步
                Article article = new Article();
                article.setId(articleId);
                article.setViewCounts(Integer.valueOf(viewCount));
                myElasticsearchRepository.save(article);
            }
        }
    }
}
